//
//  HXDRefreshControl.swift
//  weibo
//
//  Created by huxuedong on 15/12/11.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

private let refreshControlH: CGFloat = 50

//定义刷新状态枚举
enum HXDrefreshControlState: Int {
    case WillRefresh = 0
    case Refreshing = 1
    case DidRefresh = 2
}

class HXDRefreshControl: UIControl {
    
    //箭头
    private lazy var iconImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文字
    private lazy var textLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), textSize: 13)
        label.text = "下拉刷新"
        return label
    }()
    //菊花
    private lazy var juhua: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    //用于添加箭头、文字、菊花
    var scrollView: UIScrollView?
    //旧的状态
    var oldState: HXDrefreshControlState = .DidRefresh;
    //当前状态
    var currentState: HXDrefreshControlState = .DidRefresh {
        didSet {
            switch currentState {
            case .WillRefresh:
                textLabel.text = "将要刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                textLabel.text = "正在刷新"
                iconImage.hidden = true
                juhua.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var contentInset = self.scrollView?.contentInset
                    //设置顶部的内边距，修改顶部的滑动距离
                    contentInset?.top += refreshControlH
                    self.scrollView?.contentInset = contentInset!
                })
                //当refreshControl的值发生改变时，就执行HXDHomeTableViewController的loadData方法
                sendActionsForControlEvents(.ValueChanged)
            case .DidRefresh:
                textLabel.text = "完成刷新"
                iconImage.hidden = false
                juhua.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImage.transform = CGAffineTransformIdentity
                })
                if oldState == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= refreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                }
            }
            oldState = currentState
        }
    }
    
    //结束刷新
    func endRefresh() {
        currentState = .DidRefresh
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.yellowColor()
        var frame = self.frame
        //设置当前控件(HXDRefreshControl)的宽高
        frame.size = CGSizeMake(kScreenW, refreshControlH)
        //设置当前控件(HXDRefreshControl)的y值
        frame.origin.y = -refreshControlH
        self.frame = frame
        //为当前控件(HXDRefreshControl)添加子控件
        addSubview(iconImage)
        addSubview(textLabel)
        addSubview(juhua)
        iconImage.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        textLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(iconImage)
            make.leading.equalTo(iconImage.snp_trailing).offset(5)
        }
        juhua.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconImage)
        }
    }
    
    //当前控件(HXDRefreshControl)添加到某一个控件上时就会调用(newSuperview指的是HXDHomeTableViewController)
    override func willMoveToSuperview(newSuperview: UIView?) {
        //把HXDHomeTableViewController的view强转为scrollView
        if let scrollView = newSuperview as? UIScrollView {
            //KVO监听，添加观察者，forKeyPath：需要监听的属性，options：监听新值
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            self.scrollView = scrollView
            var frame = self.frame
            frame.size.width = scrollView.frame.width
            self.frame = frame
        }
    }
    
    //KVO观察到的值的改变
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let contentOffsetY = scrollView?.contentOffset.y
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        //临界值
        let conditionValue = -contentInsetTop - refreshControlH
        //判断是否拖拽
        if scrollView!.dragging {
            //将要刷新状态
            if currentState == .DidRefresh && contentOffsetY < conditionValue {
                currentState = .WillRefresh
                //完成刷新状态
            } else if currentState == .WillRefresh && contentOffsetY >= conditionValue {
                currentState = .DidRefresh
            }
        } else {
            //正在刷新状态
            if currentState == .WillRefresh {
                currentState = .Refreshing
            }
        }
    }
    
    //移除观察者
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
